
#ifndef DATATYPE_H
#define DATATYPE_H

#include <QString>

// 寄存器地址定义
#define TOTAL_REGS 37

#define REG_ID 0          // 设备ID (1个寄存器)
#define REG_NAME 1        // 设备名称 (10个寄存器)
#define REG_VALUE 11      // 设备值 (2个寄存器，浮点数)
#define REG_STATUS 13     // 设备状态 (1个寄存器)
#define REG_TIMESTAMP 14  // 时间戳 (2个寄存器)
#define REG_TEMPERATURE 16 // 温度 (2个寄存器，浮点数)
#define REG_HUMIDITY 18   // 湿度 (2个寄存器，浮点数)
#define REG_PRESSURE 20   // 压力 (1个寄存器)
#define REG_ALARM 21      // 报警状态 (1个寄存器)
#define REG_DESC 22       // 描述 (15个寄存器)

// 设备数据结构
struct DeviceData {
    int id;
    QString name;
    float value;
    bool status;
    qint32 timestamp;
    float temperature;
    float humidity;
    int pressure;
    int alarmStatus;
    QString description;
};

// 辅助函数声明
inline void stringToRegisters(const QString& str, quint16* registers, int maxRegisters) {
    QByteArray utf8Data = str.toUtf8();
    int byteIndex = 0;
    for (int i = 0; i < maxRegisters && byteIndex < utf8Data.size(); i++) {
        registers[i] = 0;
        if (byteIndex < utf8Data.size())
            registers[i] = static_cast<quint8>(utf8Data[byteIndex++]);
        if (byteIndex < utf8Data.size())
            registers[i] |= static_cast<quint8>(utf8Data[byteIndex++]) << 8;
    }
}

inline QString registersToString(const quint16* registers, int count) {
    QByteArray bytes;
    for (int i = 0; i < count; i++) {
        bytes.append(static_cast<char>(registers[i] & 0xFF));
        bytes.append(static_cast<char>((registers[i] >> 8) & 0xFF));
    }
    return QString::fromUtf8(bytes.constData());
}

inline void floatToRegisters(float value, quint16& reg1, quint16& reg2) {
    union {
        float f;
        quint32 i;
    } u;
    u.f = value;
    reg1 = u.i & 0xFFFF;
    reg2 = (u.i >> 16) & 0xFFFF;
}

inline float registersToFloat(quint16 reg1, quint16 reg2) {
    union {
        float f;
        quint32 i;
    } u;
    u.i = reg1 | (static_cast<quint32>(reg2) << 16);
    return u.f;
}

inline void int32ToRegisters(qint32 value, quint16& reg1, quint16& reg2) {
    reg1 = value & 0xFFFF;
    reg2 = (value >> 16) & 0xFFFF;
}

inline qint32 registersToInt32(quint16 reg1, quint16 reg2) {
    return reg1 | (static_cast<qint32>(reg2) << 16);
}

#endif // DATATYPE_H
